package com.zxl.register.server.socket;

import com.zxl.register.base.business.BusinessFun;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.nio.charset.StandardCharsets;

public class ReadCompletionHandler implements CompletionHandler<Integer, ByteBuffer> {

    private AsynchronousSocketChannel socketChannel;

    // 业务处理函数
    private BusinessFun businessFun;

    ReadCompletionHandler(AsynchronousSocketChannel socketChannel) {
        if (this.socketChannel == null) {
            this.socketChannel = socketChannel;
        }
    }

    ReadCompletionHandler(AsynchronousSocketChannel socketChannel,BusinessFun businessFun) {
        if (this.socketChannel == null) {
            this.socketChannel = socketChannel;
        }
        if(this.businessFun==null){
            this.businessFun=businessFun;
        }
    }

    @Override
    public void completed(Integer result, ByteBuffer attachment) {
        if(result<0){
            System.err.println(" ReadCompletionHandler completed() result < 0 !!!!  ");
            return;
        }
        attachment.flip();
        byte[] buffer = new byte[attachment.remaining()];
        attachment.get(buffer);
        String content = new String(buffer, StandardCharsets.UTF_8);
        System.out.println("received : " + content);
        // 处理业务
        businessFun.doSomeThing(socketChannel,content);
        attachment.clear();
        // 处理完之后，要继续监听read,否则同一个socket只能通信一次，无法接收到之后通过socket发送的消息
        // -------------  重要 -------------------
        socketChannel.read(attachment,attachment,this);
    }

    @Override
    public void failed(Throwable throwable, ByteBuffer attachment) {
        try {
            throwable.printStackTrace();
            System.err.println(" socket cloesd :  "+socketChannel.getRemoteAddress());
            socketChannel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
